<?php
namespace app\api\controller\v1\controller\pet;

use app\api\controller\v1\model\pet\PetInfo as Pi;
use think\Controller;

use app\api\controller\Api;

use think\Db;
use think\Image;
use think\Request;
use JPush\Client as JPush;
use think\Response;
use app\api\controller\UnauthorizedException;
use think\Validate;


class PetInfo extends api
{
    //增加宠物图片(发照片)
    public function upload_petImg($pet_id,$user_id,$text)
    {
        // 获取上传文件
        $files = Request::instance()->file('img');
        // 移动到框架应用根目录/public/uploads/ 目录下
        $info = $files->move(ROOT_PATH . 'public' . DS. 'uploads'.DS.'images');

        if($info){
            $path = '/uploads/images/' . $info->getSaveName();
            $path = str_replace('\\', '/', $path);
            if (empty($text)) {
                $res = Db::query("insert into pet_image values(null,'$pet_id','$user_id','','$path')");
            }else{
                $res = Db::query("insert into pet_image values(null,'$pet_id','$user_id','$text','$path')");
            }
            // $image = Image::open(request()->file('user_icon'));
            // // 按照原图的比例生成一个最大为200*200的缩略图并保存为thumb.png
            // $image->thumb(200, 200, Image::THUMB_CENTER)->save(ROOT_PATH . 'public' . $path);
            if (empty($res)) {
                return  $this->returnmsg(200, '图片上传成功!', 'image_url: '.$path);
            } else {
                return  $this->returnmsg(400, '图片上传失败!');
            }
        }else{
            // 上传失败获取错误信息
            echo $files->getError();
        }
    }


//上传宠物信息
    public function petinfo_upload($user_id,$pet_name,$pet_gender,$pet_brith,$pet_kind){
        switch ($pet_gender) {
            case '男':
                $pet_gender = 0;
                break;
            case '女':
                $pet_gender = 1;
                break;
        }

        $files = Request::instance()->file('img_url');
        $file = Request::instance()->file('pet_icon');
        // 移动到框架应用根目录/public/uploads/ 目录下
        // $info = $file->move(ROOT_PATH . 'public' . DS . 'uploads');
        $info = $files->move(ROOT_PATH . 'public' . DS. 'uploads'.DS.'pet_img');
        $info_icon = $file->move(ROOT_PATH . 'public' . DS. 'uploads'.DS.'pet_icon');
        //$res = db('user')->where('user_id', $data['user_id'])->setField('user_icon', $head_img_path);
        if($info && $info_icon){
            // 成功上传后 获取上传信息
            // 输出 jpg
            $path = '/uploads/pet_img/' . $info->getSaveName();
            $icon_path = '/uploads/pet_icon/' . $info_icon->getSaveName();

            $photo = $info_icon->getFilename();
            $small_path = ROOT_PATH . 'public' . DS. 'uploads'.DS.'small_pet_icon'.DS.$photo;

            $path = str_replace('\\', '/', $path);
            $icon_path = str_replace('\\', '/', $icon_path);
            $small_path = str_replace('\\', '/', $small_path);

            // $image
            $image = Image::open(request()->file('pet_icon'));
            // 按照原图的比例生成一个最大为72*72的缩略图并保存为thumb.png
            $image->thumb(72, 72, Image::THUMB_CENTER)->save($small_path);

            $len = strlen(ROOT_PATH. 'public');

            $small_path = substr_replace($small_path,'',0,$len);
            $data = ['user_id'=>$user_id,'pet_name'=>$pet_name,'pet_gender'=>$pet_gender,'pet_brith'=>$pet_brith,'pet_kind'=>$pet_kind,'pet_icon'=>$icon_path,'small_pet_icon'=>$small_path,'img_url'=>$path];
            $pet_id = Db::table('ym_pet')->insertGetId($data);

            Db::query("insert into ym_pet_hungry values(null,'$pet_id',default,default,default,default)");
            return $this->returnmsg(200,"添加宠物信息成功,请等待审核");
        }
    }


    //判断是否经过宠物认证
    public function permisstion_to_access($pet_id){
        $result = Pi::getPermisstionToAccess($pet_id);
        if ($result[0]['permisstion_to_access'] == 1) {
            return $this->returnmsg(200,'认证通过');
        }else{
            return $this->returnmsg(401,'您还没有认证宠物信息哦，快去填写信息吧');
        }
    }

//显示宠物信息
    public function show_user_petinfo($user_id,$pageno){
      $result = Pi::getShowUserPetinfo($user_id,$pageno);
        return $this->returnmsg(200,'message',$result);
    }

    // 更新宠物状态
    public function update_pet_status($pet_id,$pet_status){
        Pi::updatePetStatus($pet_id,$pet_status);
        return $this->returnmsg(200,'message');
    }

//    宠物信息
    public function pet_manage($user_id){
        $result = Pi::getPetManage($user_id);
        return $this->returnmsg(200,'宠物信息',$result);
    }

    //添加宠物或者修改宠物资料
    public function add_pet($user_id,$old_pet_id,$pet_name,$pet_gender,$pet_brith,$pet_kind){
        switch ($pet_gender) {
            case '男':
                $pet_gender = 0;
                break;
            case '女':
                $pet_gender = 1;
                break;
        }

        if (!empty($old_pet_id)) {
            $files = Request::instance()->file('img_url');
            $file = Request::instance()->file('pet_icon');
            if ($files && !$file) {
                $info = $files->move(ROOT_PATH . 'public' . DS. 'uploads'.DS.'pet_img');
                if ($info) {
                    $path = '/uploads/pet_img/' . $info->getSaveName();
                    $path = str_replace('\\', '/', $path);
                    Db::query("update ym_pet set permisstion_to_access = 0, pet_name = '$pet_name',pet_gender = '$pet_gender',pet_brith = '$pet_brith',pet_kind = '$pet_kind',img_url = '$path' where pet_id = '$old_pet_id'");
                    return $this->returnmsg(200,'修改宠物资料成功');
                }
            }elseif ($file && !$files) {
                $info_icon = $file->move(ROOT_PATH . 'public' . DS. 'uploads'.DS.'pet_icon');
                if ($info_icon) {
                    $icon_path = '/uploads/pet_icon/' . $info_icon->getSaveName();

                    $photo = $info_icon->getFilename();
                    $small_path = ROOT_PATH . 'public' . DS. 'uploads'.DS.'small_pet_icon'.DS.$photo;
                    $icon_path = str_replace('\\', '/', $icon_path);
                    $small_path = str_replace('\\', '/', $small_path);

                    // $image
                    $image = Image::open(request()->file('pet_icon'));
                    // 按照原图的比例生成一个最大为72*72的缩略图并保存为thumb.png
                    $image->thumb(72, 72, Image::THUMB_CENTER)->save($small_path);

                    $len = strlen(ROOT_PATH. 'public');

                    $small_path = substr_replace($small_path,'',0,$len);

                    Db::query("update ym_pet set permisstion_to_access = 0, pet_name = '$pet_name',pet_gender = '$pet_gender',pet_brith = '$pet_brith',pet_kind = '$pet_kind',pet_icon = '$icon_path',small_pet_icon = '$small_path' where pet_id = '$old_pet_id'");
                    return $this->returnmsg(200,'修改宠物资料成功');
                }
            }elseif (!$files && !$file) {
                Db::query("update ym_pet set permisstion_to_access = 0, pet_name = '$pet_name',pet_gender = '$pet_gender',pet_brith = '$pet_brith',pet_kind = '$pet_kind' where pet_id = '$old_pet_id'");
                return $this->returnmsg(200,'修改宠物资料成功');
            }else{
                // 移动到框架应用根目录/public/uploads/ 目录下
                $info = $files->move(ROOT_PATH . 'public' . DS. 'uploads'.DS.'pet_img');
                $info_icon = $file->move(ROOT_PATH . 'public' . DS. 'uploads'.DS.'pet_icon');

                if($info && $info_icon){
                    // 成功上传后 获取上传信息
                    // 输出 jpg
                    $path = '/uploads/pet_img/' . $info->getSaveName();
                    $icon_path = '/uploads/pet_icon/' . $info_icon->getSaveName();

                    $photo = $info_icon->getFilename();
                    $small_path = ROOT_PATH . 'public' . DS. 'uploads'.DS.'small_pet_icon'.DS.$photo;

                    $path = str_replace('\\', '/', $path);
                    $icon_path = str_replace('\\', '/', $icon_path);
                    $small_path = str_replace('\\', '/', $small_path);

                    // $image
                    $image = Image::open(request()->file('pet_icon'));
                    // 按照原图的比例生成一个最大为72*72的缩略图并保存为thumb.png
                    $image->thumb(72, 72, Image::THUMB_CENTER)->save($small_path);

                    $len = strlen(ROOT_PATH. 'public');

                    $small_path = substr_replace($small_path,'',0,$len);

                    Db::query("update ym_pet set permisstion_to_access = 0, pet_name = '$pet_name',pet_gender = '$pet_gender',pet_brith = '$pet_brith',pet_kind = '$pet_kind',pet_icon = '$icon_path',small_pet_icon = '$small_path',img_url = '$path' where pet_id = '$old_pet_id'");
                    return $this->returnmsg(200,'修改宠物资料成功,请等待审核');
                }
            }
        }else{

            $files = Request::instance()->file('img_url');
            $file = Request::instance()->file('pet_icon');
            // 移动到框架应用根目录/public/uploads/ 目录下
            // $info = $file->move(ROOT_PATH . 'public' . DS . 'uploads');
            $info = $files->move(ROOT_PATH . 'public' . DS. 'uploads'.DS.'pet_img');
            $info_icon = $file->move(ROOT_PATH . 'public' . DS. 'uploads'.DS.'pet_icon');
            //$res = db('user')->where('user_id', $data['user_id'])->setField('user_icon', $head_img_path);
            if($info && $info_icon){
                // 成功上传后 获取上传信息
                // 输出 jpg
                $path = '/uploads/pet_img/' . $info->getSaveName();
                $icon_path = '/uploads/pet_icon/' . $info_icon->getSaveName();

                $photo = $info_icon->getFilename();
                $small_path = ROOT_PATH . 'public' . DS. 'uploads'.DS.'small_pet_icon'.DS.$photo;

                $path = str_replace('\\', '/', $path);
                $icon_path = str_replace('\\', '/', $icon_path);
                $small_path = str_replace('\\', '/', $small_path);

                // $image
                $image = Image::open(request()->file('pet_icon'));
                // 按照原图的比例生成一个最大为72*72的缩略图并保存为thumb.png
                $image->thumb(72, 72, Image::THUMB_CENTER)->save($small_path);

                $len = strlen(ROOT_PATH. 'public');

                $small_path = substr_replace($small_path,'',0,$len);
                $data = ['user_id'=>$user_id,'pet_name'=>$pet_name,'pet_gender'=>$pet_gender,'pet_brith'=>$pet_brith,'pet_kind'=>$pet_kind,'pet_icon'=>$icon_path,'small_pet_icon'=>$small_path,'img_url'=>$path];
                $pet_id = Db::table('ym_pet')->insertGetId($data);

                Db::query("insert into ym_pet_hungry values(null,'$pet_id',default,default,default,default)");
                return $this->returnmsg(200,"添加宠物信息成功,请等待审核");
            }
        }
    }


//    删除宠物
    public function delete_pet($pet_id){
        Pi::deletePet($pet_id);
        return $this->returnmsg(200,'删除宠物成功');
    }


    //修改宠物资料
    public function edit_pet_info($pet_id){
        $result = Pi::getEditPetInfo($pet_id);
        return $this->returnmsg(200,'pet_info',$result);
    }


    //查看连续喂养了多少天
    public function continue_day($day_list){
        $continue_day = Pi::getContinueDay($day_list);
        return $continue_day;    //输出连续几天
    }

    //宠物详情
    public function get_petInfo($user_id,$fP1Lat, $fP1Lon, $fP2Lat, $fP2Lon){
//        $res = Pi::getPetInfo($user_id,$fP1Lat, $fP1Lon, $fP2Lat, $fP2Lon);
//        return $this->returnmsg(200,'petInfo',$res);



        $result = Db::query("select a.pet_id,a.user_id,a.pet_name,a.pet_brith,a.pet_kind,a.pet_gender,a.pet_icon,b.user_icon,b.fans_count,b.fosterage_or_not from ym_pet as a join user_info as b on a.user_id = b.user_id  where a.user_id = '$user_id' and a.permisstion_to_access = 1");
        $pet_id = array();
        //对用户所有宠物进行处理
        foreach ($result as $key => $value) {
            $pet_id[] = $result[$key]['pet_id'];
            $lengh = count($pet_id);
            for ($i=0; $i < $lengh ; $i++) {
                $count = Db::query("select count(1) as count from ym_pet_appointment where pet_id = '$pet_id[$i]'");
                $result[$key]['appointment_count'] = $count[0]['count'];
                //获取约过的人的头像，没有做过滤
                if ($count[0]['count'] <= 5) {
                    $user_icons = Db::table('ym_pet_appointment')->field('user_icon')->where('owned_user_id',$user_id)->where('pet_id',$pet_id[$i])->select();
                    $user_icon = $user_icons[$i]['user_icon'];
                }else{
                    $user_icons = Db::table('ym_pet_appointment')->field('user_icon')->where('owned_user_id',$user_id)->where('pet_id',$pet_id[$i])->limit(5)->select();

                }
            }
            $result[$key]['user_icons'] = $user_icons;
        }

        $distance = $this->calculate_distance($fP1Lat, $fP1Lon, $fP2Lat, $fP2Lon);
        $res = ['pet_info'=>$result,'distance'=>$distance];
        return $this->returnmsg(200,'petInfo',$res);



    }


    //是否同意共享自己的宠物
    public function appoint_agree_or_not($user_id,$type){
        if ($type == 1) {
            Db::query("update user_info set share_pet_agree_or_not = 1 where user_id = '$user_id'");
            return $this->returnmsg(200,'已开启');
        }else{
            Db::query("update user_info set share_pet_agree_or_not = 0 where user_id = '$user_id'");
            return $this->returnmsg(200,'已关闭');
        }
    }


//修改宠物资料
    public function modify_pet_info($pet_id,$pet_name,$pet_brith,$pet_kind,$pet_gender){
        switch ($pet_gender) {
            case '男':
                $pet_gender = 0;
                break;
            case '女':
                $pet_gender = 1;
                break;
        }
        $file = Request::file('pet_icon');
        if ($file) {//如果修改了头像

            $info_icon = $file->move(ROOT_PATH . 'public' . DS. 'uploads'.DS.'pet_icon');
            //$res = db('user')->where('user_id', $data['user_id'])->setField('user_icon', $head_img_path);
            if($info_icon){
                // 成功上传后 获取上传信息
                // 输出 jpg
                $icon_path = '/uploads/pet_icon/' . $info_icon->getSaveName();

                $photo = $info_icon->getFilename();
                $small_path = ROOT_PATH . 'public' . DS. 'uploads'.DS.'small_pet_icon'.DS.$photo;

                $icon_path = str_replace('\\', '/', $icon_path);
                $small_path = str_replace('\\', '/', $small_path);

                // $image
                $image = Image::open(request()->file('pet_icon'));
                // 按照原图的比例生成一个最大为72*72的缩略图并保存为thumb.png
                $image->thumb(72, 72, Image::THUMB_CENTER)->save($small_path);

                $len = strlen(ROOT_PATH. 'public');//获取需要截取的路径

                $small_path = substr_replace($small_path,'',0,$len);//将上面的路径截取

                Db::query("update ym_pet set pet_name = '$pet_name',pet_brith = '$pet_brith',pet_kind = '$pet_kind',pet_icon = '$icon_path',small_pet_icon = '$small_path' where pet_id = '$pet_id'");
                return $this->returnmsg(200,'修改宠物信息成功');
            }
        }else{//没有修改头像，直接将参数修改进数据库
            Db::query("update ym_pet set pet_name = '$pet_name',pet_brith = '$pet_brith',pet_kind = '$pet_kind' where pet_id = '$pet_id'");
            return $this->returnmsg(200,'修改宠物信息成功');
        }
    }


    //返回是否同意共享宠物 json
    public function judgement_appoint($user_id){
        $result = Db::query("select share_pet_agree_or_not from user_info where user_id = '$user_id'");
        return json($result[0]);
    }





//计算距离
    public function calculate_distance($fP1Lat, $fP1Lon, $fP2Lat, $fP2Lon){
        $fEARTH_RADIUS = 6378137;
        //角度换算成弧度
        $fRadLon1 = deg2rad($fP1Lon);
        $fRadLon2 = deg2rad($fP2Lon);
        $fRadLat1 = deg2rad($fP1Lat);
        $fRadLat2 = deg2rad($fP2Lat);
        //计算经纬度的差值
        $fD1 = abs($fRadLat1 - $fRadLat2);
        $fD2 = abs($fRadLon1 - $fRadLon2);
        //距离计算
        $fP = pow(sin($fD1/2), 2) +
            cos($fRadLat1) * cos($fRadLat2) * pow(sin($fD2/2), 2);
        return round(floatval($fEARTH_RADIUS * 2 * asin(sqrt($fP))/1000),2);
    }










//推送全部
    public function push($user_id,$message){
        $appkey = 'a3d1bad973276db7cee3f40a';
        $master_secret = 'ac5c6c6b1101643082c88913';
        $client = new JPush($appkey,$master_secret);
        $r_id = Db::query("select registration_id from ym_device_no where user_id = '$user_id'");
        $registration_id = $r_id[0]['registration_id'];

        $push = $client->push();
        $push->setPlatform('all');
        //别名
        $push->addAlias($user_id);
        //设备号
        $push->addRegistrationId($registration_id);
        // $push->iosNotification();
        $push->iosNotification($message, [
            'sound' => 'sound.cat',
            'badge' => '+1',

        ]);
        $push->options(array(
            "apns_production" => true
        ));
        // try {
        $push->send();

    }


}